<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <!-- <div style="height: 50px">
      <el-button
        type="primary"
        plain
        @click="openBatchEditDialog"
        :disabled="selectedRows.length === 0 || isSupplierDisabled"
        >批量选择供应商</el-button
      >
    </div> -->
    <el-table
      ref="tableRef"
      :data="formData"
      show-summary
      :summary-method="getSummaries"
      class="-mt-10px"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <!-- <el-table-column width="60" label="选择" type="selection" /> -->
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              :filter-method="handleProductFilter"
              @change="onChangeProduct($event, $index)"
              placeholder="请选择产品"
              :disabled="isOtherDisabled"
            >
              <!-- 禁用状态下显示已选产品名称 -->
              <!-- <el-option
                v-if="isOtherDisabled"
                :label="getProductName(row.productId)"
                :value="row.productId"
              /> -->
              <!-- 正常状态下显示过滤后的产品列表 -->
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="单位" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            {{ row.productUnitName || getProductUnit(row.productId) }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="规格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productStandard`" class="mb-0px!">
            {{ getProductStandardName(row.productId) }}
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 新增价格列 -->
<!--      <el-table-column label="价格" min-width="150">-->
<!--        <template #default="{ row, $index }">-->
<!--          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">-->
<!--            {{ getProductPrice(row.productId) }}-->
<!--          </el-form-item>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <!--  <el-table-column label="供应商" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.supplierId`"
            :rules="formRules.supplierId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.supplierId"
              clearable
              filterable
              placeholder="请选择供应商"
              class="mb-0px!"
              :filter-method="handleSupplierFilter"
              :disabled="isSupplierDisabled"
            >
               禁用状态下显示已选供应商名称<el-option
                v-if="isOtherDisabled"
                :label="getSupplierName(row.supplierId)"
                :value="row.supplierId"
              />  正常状态下显示过滤后的供应商列表
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>-->

      <el-table-column label="数量" prop="count" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="0"
              :precision="0"
              class="!w-100%"
              :disabled="isOtherDisabled"
            />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" :disabled="isOtherDisabled" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="100" fixed="right">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link type="primary" :disabled="isOtherDisabled"
            >删除此条</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-form>

  <el-row justify="center" class="mt-3" v-if="!isOtherDisabled">
    <el-button @click="handleAdd" round>+ 添加采购产品</el-button>
  </el-row>

  <!-- 批量修改供应商弹窗 -->
  <Dialog
    v-model="batchEditDialogVisible"
    title="批量修改供应商"
    width="500px"
    :before-close="handleDialogClose"
  >
    <el-form ref="batchFormRef" :model="batchForm" :rules="batchFormRules" label-width="120px">
      <el-form-item label="目标供应商" prop="targetSupplierId">
        <el-select
          v-model="batchForm.targetSupplierId"
          clearable
          filterable
          placeholder="请选择供应商"
          class="w-100%"
          :filter-method="handleSupplierFilter"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="confirmBatchEdit">确认修改</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { StockApi } from '@/api/erp/stock/stock'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import { erpCountFormatter, erpPriceInputFormatter, erpPriceMultiply, getSumValue } from '@/utils'
import { ElMessage } from 'element-plus'

// 接收父组件Props，优化类型定义
const props = defineProps<{
  items?: any[] // 允许undefined，避免初始报错
  isOtherDisabled: boolean // 非供应商功能禁用（产品/数量/备注等）
  isSupplierDisabled: boolean // 供应商功能禁用（仅详情页）
}>()

// 表单基础状态
const formLoading = ref(false)
const formData = ref<any[]>([])
// 修复：表单Ref应为单个对象（Element Plus表单要求）
const formRef = ref(null)

// -------------------------- 核心优化：产品下拉框回显问题修复 --------------------------
const productList = ref([] as Array<any>) // 下拉显示用产品列表
const productAllList = ref<ProductVO[]>([]) // 完整产品列表（缓存）

/** 1. 加载完整产品列表（仅加载一次，带错误处理） */
const loadAllProducts = async () => {
  if (productAllList.value.length > 0) return productAllList.value
  try {
    const data = await ProductApi.getProductSimpleList()
    productAllList.value = data || []
    return data
  } catch (error) {
    ElMessage.error('加载产品列表失败，请重试')
    productAllList.value = []
    return []
  }
}

/** 2. 确保已选产品在下拉列表中（回显补全） */
const ensureSelectedProductInList = async () => {
  await loadAllProducts()
  // 提取所有已选产品ID（去空）
  const selectedProductIds = formData.value.map((item) => item.productId).filter(Boolean)
  selectedProductIds.forEach((id) => {
    const isExist = productList.value.some((item) => item.id === id)
    if (!isExist) {
      const product = productAllList.value.find((item) => item.id === id)
      if (product) productList.value.push(product)
    }
  })
}

/** 3. 产品过滤方法（合并已选+过滤结果） */
const handleProductFilter = async (query?: string) => {
  await loadAllProducts()

  // 提取已选产品（避免回显丢失）
  const selectedProducts = formData.value
    .map((item) => productAllList.value.find((p) => p.id === item.productId))
    .filter(Boolean)

  // 按查询条件过滤（首屏200条性能优化）
  let filteredProducts: ProductVO[] = []
  if (!query) {
    filteredProducts = [...productAllList.value].slice(0, 200)
  } else {
    filteredProducts = productAllList.value.filter((p) =>
      p.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并去重
  productList.value = Array.from(
    new Map([...filteredProducts, ...selectedProducts].map((p) => [p.id, p])).values()
  )
}

/** 4. 根据产品ID获取名称（用于禁用状态下回显） */
const getProductName = (productId: any): string => {
  const product = productAllList.value.find((item) => item.id === productId)
  return product?.name || ''
}

/** 5. 根据产品ID获取单位（用于单位回显） */
const getProductUnit = (productId: any): string => {
  const product = productAllList.value.find((item) => item.id === productId)
  return product?.unitName || ''
}

/**产品规格回显**/
const getProductStandardName = (productId: any): string => {
  if (!productId) return ''
  const product = productAllList.value.find((item) => item.id === productId)
  return product?.standard || ''
}

/** 产品价格回显（新增：对应价格列显示） */
const getProductPrice = (productId: any): string => {
  if (!productId) return ''
  const product = productAllList.value.find((item) => item.id === productId)
  return product?.productPrice ? erpPriceInputFormatter(product.productPrice) : ''
}

// -----------------------------------------------------------------------------------

// -------------------------- 核心优化：供应商下拉框回显问题修复 --------------------------
const supplierList = ref([] as Array<any>) // 下拉显示用供应商列表
const supplierAllList = ref<SupplierVO[]>([]) // 完整供应商列表（缓存）

/** 1. 加载完整供应商列表（仅加载一次，带错误处理） */
const loadAllSuppliers = async () => {
  if (supplierAllList.value.length > 0) return supplierAllList.value
  try {
    const data = await SupplierApi.getSupplierSimpleList()
    supplierAllList.value = data || []
    return data
  } catch (error) {
    ElMessage.error('加载供应商列表失败，请重试')
    supplierAllList.value = []
    return []
  }
}

/** 2. 确保已选供应商在下拉列表中（回显补全） */
const ensureSelectedSupplierInList = async () => {
  await loadAllSuppliers()
  // 提取所有已选供应商ID（去空）
  const selectedSupplierIds = formData.value.map((item) => item.supplierId).filter(Boolean)
  selectedSupplierIds.forEach((id) => {
    const isExist = supplierList.value.some((item) => item.id === id)
    if (!isExist) {
      const supplier = supplierAllList.value.find((item) => item.id === id)
      if (supplier) supplierList.value.push(supplier)
    }
  })
}

/** 3. 供应商过滤方法（合并已选+过滤结果） */
const handleSupplierFilter = async (query?: string) => {
  await loadAllSuppliers()

  // 提取已选供应商（避免回显丢失）
  const selectedSuppliers = formData.value
    .map((item) => supplierAllList.value.find((s) => s.id === item.supplierId))
    .filter(Boolean)

  // 按查询条件过滤（首屏200条性能优化）
  let filteredSuppliers: SupplierVO[] = []
  if (!query) {
    filteredSuppliers = [...supplierAllList.value].slice(0, 200)
  } else {
    filteredSuppliers = supplierAllList.value.filter((s) =>
      s.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并去重
  supplierList.value = Array.from(
    new Map([...selectedSuppliers, ...filteredSuppliers].map((s) => [s.id, s])).values()
  )
}

/** 4. 根据供应商ID获取名称（用于禁用状态下回显） */
const getSupplierName = (supplierId: any): string => {
  const supplier = supplierAllList.value.find((item) => item.id === supplierId)
  return supplier?.name || ''
}
// -----------------------------------------------------------------------------------

// 表单校验规则（优化触发方式，适配下拉框）
const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'change' }], // 改为change触发
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'change' }], // 改为change触发
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  count: [
    { required: true, message: '产品数量不能为空', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量不能小于1', trigger: 'blur' }
  ]
})

// 批量修改供应商相关状态
const tableRef = ref(null)
const selectedRows = ref<any[]>([])
const batchEditDialogVisible = ref(false)
const batchFormRef = ref(null)
const batchForm = reactive({
  targetSupplierId: undefined
})
const batchFormRules = reactive({
  targetSupplierId: [{ required: true, message: '请选择目标供应商', trigger: 'change' }] // 改为change触发
})

/** 初始化设置采购项（优化：加载数据后补全回显） */
watch(
  () => props.items,
  async (val) => {
    formData.value = val || [] // 处理undefined，避免空数组报错
    // 补全已选产品和供应商的回显
    await Promise.all([ensureSelectedProductInList(), ensureSelectedSupplierInList()])
    // 初始化已有数据的总价计算
    formData.value.forEach((item) => {
      const price = item.productPrice || 0
      const count = item.count || 1
      const taxPercent = item.taxPercent || 0
      item.totalProductPrice = erpPriceMultiply(price, count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, taxPercent / 100)
      item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
    })
  },
  { immediate: true, deep: true }
)

/** 监听采购项变化，自动计算金额（优化容错） */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) return
    val.forEach((item) => {
      // 处理undefined值，避免计算报错
      const price = item.productPrice || 0
      const count = item.count || 0
      const taxPercent = item.taxPercent || 0

      item.totalProductPrice = erpPriceMultiply(price, count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, taxPercent / 100)
      item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
    })
  },
  { deep: true, flush: 'post' } // 确保DOM更新后执行，保证数据同步
)

/** 表格合计逻辑（优化：处理undefined值+价格列合计totalPrice） */
const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    // 价格列（index=4）回显totalPrice合计
    if (index === 4) {
      const totalPriceSum = getSumValue(data.map((item) => Number(item.totalPrice || 0)))
      sums[index] = erpPriceInputFormatter(totalPriceSum)
    }
    // 只对数值型字段合计，处理undefined为0
    else if (
      ['count', 'totalProductPrice', 'taxPrice', 'totalPrice'].includes(column.property as string)
    ) {
      const sum = getSumValue(data.map((item) => Number(item[column.property] || 0)))
      sums[index] =
        column.property === 'count' ? erpCountFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

/** 新增采购项（优化：初始化价格默认值） */
const handleAdd = () => {
  const row = {
    id: Date.now(), // 用时间戳确保唯一ID
    productId: undefined,
    productUnitName: undefined,
    productStandard: undefined,
    productBarCode: undefined,
    productPrice: 0, // 初始化价格为0，避免计算异常
    stockCount: 0, // 初始库存为0
    count: 1, // 默认数量1
    totalProductPrice: 0,
    taxPercent: 0, // 默认税率0
    taxPrice: 0,
    totalPrice: 0,
    remark: ''
  }
  formData.value.push(row)
}

/** 删除采购项（优化：边界校验） */
const handleDelete = (index: number) => {
  if (index < 0 || index >= formData.value.length) return // 避免越界
  formData.value.splice(index, 1)
}

/** 处理产品变更（优化：同步产品信息+加载库存） */
const onChangeProduct = async (productId: any, index: number) => {
  await loadAllProducts()
  const product = productAllList.value.find((item) => item.id === productId)
  const row = formData.value[index] || {}

  if (product) {
    // 同步产品单位、条码、采购价（触发响应式更新）
    formData.value.splice(index, 1, {
      ...row,
      productId,
      productUnitName: product.unitName,
      productStandard: product.productStandard,
      productBarCode: product.barCode,
      productPrice: product.productPrice || 0,
      // 重新计算总价
      totalProductPrice: erpPriceMultiply(product.productPrice || 0, row.count || 1),
      taxPrice: erpPriceMultiply(
        erpPriceMultiply(product.productPrice || 0, row.count || 1),
        (row.taxPercent || 0) / 100
      ),
      totalPrice:
        erpPriceMultiply(product.productPrice || 0, row.count || 1) +
        erpPriceMultiply(
          erpPriceMultiply(product.productPrice || 0, row.count || 1),
          (row.taxPercent || 0) / 100
        )
    })
    // 加载产品库存
    await setStockCount(formData.value[index])
  }
}

/** 加载产品库存（优化：错误处理） */
const setStockCount = async (row: any) => {
  if (!row.productId) {
    row.stockCount = 0
    return
  }
  try {
    const count = await StockApi.getStockCount(row.productId)
    row.stockCount = count || 0
  } catch (error) {
    ElMessage.warning('获取库存失败，默认显示0')
    row.stockCount = 0
  }
}

/** 表格选中行变化 */
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val
}

/** 打开批量修改弹窗（优化：重置表单） */
const openBatchEditDialog = () => {
  batchForm.targetSupplierId = undefined
  batchFormRef.value?.resetFields()
  batchEditDialogVisible.value = true
}

/** 关闭批量修改弹窗 */
const handleDialogClose = () => {
  batchEditDialogVisible.value = false
  batchFormRef.value?.resetFields()
}

/** 确认批量修改供应商（优化：高效更新+清空选中） */
const confirmBatchEdit = async () => {
  if (!batchFormRef.value) return
  // 表单校验
  try {
    await batchFormRef.value.validate()
  } catch (error) {
    return
  }

  // 批量更新选中行的供应商ID
  selectedRows.value.forEach((selectedRow) => {
    const index = formData.value.findIndex((item) => item.id === selectedRow.id)
    if (index !== -1) {
      formData.value[index].supplierId = batchForm.targetSupplierId
    }
  })

  // 重置状态
  tableRef.value?.clearSelection() // 清空表格选中UI
  selectedRows.value = [] // 清空选中数据
  handleDialogClose()
  ElMessage.success('供应商批量修改成功')
}

/** 表单校验（修复：适配单个表单Ref） */
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}
defineExpose({ validate })

/** 初始化（优化：并行加载数据+默认添加行） */
onMounted(async () => {
  formLoading.value = true
  try {
    // 并行加载产品和供应商完整列表（提升速度）
    await Promise.all([loadAllProducts(), loadAllSuppliers()])
    // 初始化下拉显示列表
    await Promise.all([handleProductFilter(), handleSupplierFilter()])
    // 补全已选数据回显
    await Promise.all([ensureSelectedProductInList(), ensureSelectedSupplierInList()])
    // 初始无数据时默认添加一行
    if (formData.value.length === 0) {
      handleAdd()
    }
  } catch (error) {
    ElMessage.error('初始化失败，请刷新重试')
    console.error('初始化错误:', error)
  } finally {
    formLoading.value = false
  }
})
</script>
